//
//  HNMyEarningsController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2017/1/5.
//  Copyright © 2017年 好牛. All rights reserved.
//

#import "HNMyEarningsController.h"
#import "HNMyEarningCell.h"

@interface HNMyEarningsController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic,strong)NSArray *dataSource;

////pickBackView////
@property (nonatomic,strong) UIView *pickBackView;
@property (nonatomic,strong) UIPickerView *pickerView;

@property(nonatomic,assign) NSArray *pickerDataSource;
@property(nonatomic,assign) id   delegate;
@property(nonatomic)   BOOL   showsSelectionIndicator;//是否要显示选中的指示器
@property(nonatomic,assign) NSInteger numberOfComponents;//列


@property (nonatomic,strong) NSMutableArray *proTimeList;

@property (nonatomic,strong) NSString *sureTextStr;

@end

@implementation HNMyEarningsController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (IBAction)backAction:(UIButton *)sender {
     [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 提现
- (IBAction)withDrawalsAction:(UIButton *)sender {
    
    
}

#pragma mark - 选择时间
- (IBAction)choiceTimeAction:(UIButton *)sender {
    if (_pickBackView.isHidden) {
        [_pickBackView setHidden:NO];
        [self getFlowingWaterTimeList];
    }else{
        [_pickBackView setHidden:YES];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的收入";
}

-(void)drawView{
    _dataSource = [NSMutableArray array];
    
    _proTimeList = [NSMutableArray array];
    
    [self.headBackgroundView setBackgroundColor:RGB(91, 205, 113)];
    
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_tableView];

    _pickBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
    [_pickBackView setHidden:YES];
    
    [self.view addSubview:_pickBackView];

}


-(void)createPickView{
    [_pickBackView removeFromSuperview];
    _pickBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
    _pickBackView.backgroundColor = RGBA(255, 255, 255, 0.3);
    UITapGestureRecognizer *tapGR=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenPickBackView)];

    //3.将手势与试图关联起来
    [_pickBackView addGestureRecognizer:tapGR];
    [self.view addSubview:_pickBackView];
    
    // 选择框
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, _pickBackView.frame.size.height- 225, _pickBackView.frame.size.width, 180)];
    _pickerView.backgroundColor = RGBJ(220);
    // 显示选中框
    _pickerView.showsSelectionIndicator=YES;
    _pickerView.dataSource = self;
    _pickerView.delegate = self;
    
    [_pickBackView addSubview:_pickerView];
  
    
    
    UIView *btnView = [[UIView alloc]initWithFrame:CGRectMake(0, _pickBackView.frame.size.height - 45, _pickBackView.frame.size.width, 45)];
    btnView.backgroundColor = [UIColor whiteColor];
    [_pickBackView addSubview:btnView];
    
    UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [clickBtn setTitle:@"取消" forState:UIControlStateNormal];
    [clickBtn setFont:[UIFont systemFontOfSize:15]];
    [clickBtn setBackgroundColor:[UIColor whiteColor]];
    [clickBtn setTitleColor:RGB(85, 209, 91) forState:UIControlStateNormal];
    clickBtn.frame = CGRectMake(0, 0, btnView.frame.size.width/2, btnView.frame.size.height);
    [clickBtn addTarget:self action:@selector(hiddenPickBackView) forControlEvents:UIControlEventTouchUpInside];
    [btnView addSubview:clickBtn];
    
    UIButton *clickBtn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [clickBtn2 setTitle:@"确定" forState:UIControlStateNormal];
    [clickBtn2 setFont:[UIFont systemFontOfSize:15]];
    [clickBtn2 setBackgroundColor:RGB(85, 209, 91)];
    [clickBtn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    clickBtn2.frame = CGRectMake(btnView.frame.size.width/2, 0, btnView.frame.size.width/2, btnView.frame.size.height);
    [clickBtn2 addTarget:self action:@selector(surePickBackView) forControlEvents:UIControlEventTouchUpInside];
    [btnView addSubview:clickBtn2];
   
}

-(void)hiddenPickBackView{
    [_pickBackView setHidden:YES];
}

-(void)surePickBackView{
     _choiceTextLabel.text = _sureTextStr;
     [_pickBackView setHidden:YES];
    [self getFlowingWaterDetailList];
  
}


-(void)initData{
    [self getEarningData];
}

#pragma -mark TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *detailDic = [NSDictionary dictionaryWithDictionary:_dataSource[indexPath.row]];
    
//    afterFreezingMoney = 0;
//    afterMoney = "0.01";
//    createTime = "2017-02-15 17:28:24";
//    flowId = 1;
//    flowRemark = "\U54a8\U8be2\U8ba2\U5355\U5b8c\U6210";
//    flowSource = 170123025298508;
//    flowType = 0;
//    freezingMoney = 0;
//    money = "0.01";
//    userId = 10011;
    static NSString *CellIdentifier = @"HNMyEarningCell";
    
    HNMyEarningCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary *flowSource = [AppConfig dictionaryWithJsonString:[NSString stringWithFormat:@"%@",[detailDic objectForKey:@"flowSource"]]];
    NSLog(@"%@",flowSource);
    
    NSString *type = [NSString stringWithFormat:@"%@",[flowSource objectForKey:@"type"]];
    if (![AppConfig isNULL:type]) {
//        if ([type isEqualToString:@"0"]) {
//             [cell.cellImage setImage:[UIImage imageNamed:@"千库网-消息中心.png"]];
//        }else if ([type isEqualToString:@"1"]) {
            NSString *imageStr = [NSString stringWithFormat:@"%@",[flowSource objectForKey:@"buyerPhoto"]];
            NSLog(@"%@",imageStr);
            
            if ([AppConfig isStrNull:imageStr]) {
                [cell.cellImage setImage:[UIImage imageNamed:@"千库网-消息中心.png"]];
            }else{
                [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,imageStr]] placeholderImage:[UIImage imageNamed:@"千库网-消息中心.png"]];
            }
//        }
    }
    
    cell.cellName.text = [NSString stringWithFormat:@"%@",[detailDic objectForKey:@"flowRemark"]];
    cell.cellTime.text = [NSString stringWithFormat:@"%@",[detailDic objectForKey:@"createTime"]];
    cell.cellFloeingWater.text = [NSString stringWithFormat:@"+%@",[detailDic objectForKey:@"integral"]];
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}


#pragma Mark -- UIPickerViewDataSource
// pickerView 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// pickerView 每列个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
//    if (component == 0) {
//        return [_proTitleList count];
//    }
    
    return [_proTimeList count];
}

#pragma Mark -- UIPickerViewDelegate
// 每列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
//    if (component == 1) {
//        return 100;
//    }
    return 200;
}
// 返回选中的行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//    if (component == 0) {
//        NSString  *_proNameStr = [_proTitleList objectAtIndex:row];
//        NSLog(@"nameStr=%@",_proNameStr);
//    } else {
    NSDictionary *proTimeDic = [NSDictionary dictionaryWithDictionary:_proTimeList[row]];
    NSString *dateStr = [NSString stringWithFormat:@"%@",[proTimeDic objectForKey:@"date"]];
    
        NSLog(@"_proTimeStr=%@",dateStr);
    
//    }
    
}

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSDictionary *proTimeDic = [NSDictionary dictionaryWithDictionary:_proTimeList[row]];
    NSString *dateStr = [NSString stringWithFormat:@"%@",[proTimeDic objectForKey:@"date"]];
    _sureTextStr = dateStr;
        return dateStr;
        
//    }
}


#pragma mark - 获取总收入
-(void)getEarningData{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_Earning_detail parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"更新总收入失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSDictionary *obj = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            NSLog(@"%@",obj);
            float money = [[NSString stringWithFormat:@"%@",[obj objectForKey:@"money"]] floatValue];
            _earning.text = [NSString stringWithFormat:@"%.2f",money];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取总收入失败"];
    }];
    
}

#pragma mark - 流水时间列表
-(void)getFlowingWaterTimeList{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_Earning_FlowingWater_timeList parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取流水时间列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray *obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"%@",obj);
   
            _proTimeList = [NSMutableArray arrayWithArray:obj];
            NSLog(@"%@",_proTimeList);
            
        [self createPickView];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取流水时间列表失败"];
    }];
    
}

#pragma mark - 获取流水详情列表
-(void)getFlowingWaterDetailList{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:_choiceTextLabel.text forKey:@"createTime"];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_Earning_FlowingWater_detailList parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"更新总收入失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSMutableArray *obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"%@",obj);
            _dataSource = obj;
            
             [self.tableView reloadData];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取总收入失败"];
    }];
    
}








@end
